package gui.workshop;

import gui.App;
import gui.InfoPanel;
import gui.Printer;
import gui.dialogs.Confirm;
import gui.popup.SubscriptionPopup_selectClient;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import models.Client;
import models.Subscription;
import models.Workshop;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.ExpandBar;
import org.eclipse.swt.widgets.Text;


class SubscriptionPanelOfWorkshop extends InfoPanel {
	private App app;
	private SubscriptionPopup_selectClient popup;
	
	private Workshop workshop;
	private List<Subscription> subscriptions;

	private Text totalText;
	private Button addButton;
	private Button printButton;
	private List<Text> guiList_text = new ArrayList<Text>();
	private List<Button> guiList_button = new ArrayList<Button>();
	
	/**
	 * Constructor of the subscriptionPanelOfWorkshop creates the subscription field and initializes the subscription popup.
	 * @param app
	 * @param infoBar ExpandBar
	 */
	public SubscriptionPanelOfWorkshop(final App app, ExpandBar infoBar) {
		super(infoBar, "Inschrijvingen");
		this.app = app;
		this.popup = new SubscriptionPopup_selectClient(app);
		
		build();
		updateGui();
	}
	
	/**
	 * This function builds the top of the ExpandBar.
	 */
	private void build() {
		setLayout(new GridLayout(3, false));
		
		totalText = new Text(this, SWT.READ_ONLY | SWT.WRAP | SWT.MULTI);
		GridData expandHor = new GridData();
		expandHor.grabExcessHorizontalSpace = true;
		expandHor.horizontalAlignment = GridData.FILL;
		totalText.setLayoutData(expandHor);
		
		printButton = new Button(this, SWT.PUSH);
		printButton.setText("Print");	
		printButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {				
				printEvent();	
			}
		});	
		
		addButton = new Button(this, SWT.PUSH);
		addButton.setText("+");	
		addButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {	
				addSubscriptionEvent();	
			}
		});		
	}
	
	/**
	 * This function refreshes the total subscription field
	 */
	private void updateGui() {
		disposeGuiList();
		if (workshop == null) {
			totalText.setText("Selecteer een workshop");
			printButton.setEnabled(false);
			addButton.setEnabled(false);
		}
		else {	
			setTotalText("Total: " + subscriptions.size() + " / " + workshop.getParticipantsMax());
			printButton.setEnabled(true);
			addButton.setEnabled(true);
			for (final Subscription subscription : subscriptions) {
				addToGuiList(subscription);			
			}
		}
		// Fix for diappearng entries when selecting the same workshop agian and again
		this.layout();
		updateHeight();
	}
	
	/**
	 * This function Changes the selected workshop and updates the subscription field.
	 * 
	 * @param workshop Selected workshop
	 */
	public void setWorkshop(Workshop workshop) {
		this.workshop = workshop;
		subscriptions = app.getSubscriptionList().getSubscriptions(workshop);
		updateGui();
	}
	
	/**
	 * This function parses the workshopdata to a HTML text and let you print the subscriptionList.
	 */
	public void printEvent() {
		String title = "Inschrijvingen voor workshop " + workshop.getTitle() + " (" + workshop.getDateString() + ")";
		String contents = "<H1>" + title + "</H1>";
		
		contents += "<TABLE border='1'>";
		contents += "<TR><TH>Naam</TH><TH>Telefoonnummer</TH><TH>Email</TH></TR>";
		for (Client client : app.getSubscriptionList().getSubscriptedClients(workshop)) {
			contents += "<TR>";
			contents += "<TD>" + client.getGivenname() + " " + client.getLastname() + "</TD>";
			contents += "<TD>" + client.getPhone() + "</TD>";
			contents += "<TD>" + client.getEmail() + "</TD>";
			contents += "</TR>";
		}
		contents += "</TABLE>";
		Printer.print(title, contents);
	}

	/**
	 * This function start the subscription algorithm for the selected workshop. It gives a warning if the maximum participants is reached.
	 */
	private void addSubscriptionEvent() {
		// Check for maximum capacity
		int subscriptions = app.getSubscriptionList().getSubscriptions(workshop).size();
		if (subscriptions >= workshop.getParticipantsMax()) {
			boolean cont = new Confirm(getShell(), 
				"Maximumcapaciteit bereikt", 
				"De maximumcapaciteit is al bereikt. Toch doorgaan?"
			).open().accepted;
			if (!cont) {
				return;
			}
		}
		Subscription subscription = popup.open_selectClient(workshop);
		if (subscription != null) {
			try {
				app.getSubscriptionList().add(subscription);
			} catch (SQLException e1) {
				app.dbCommunicationException(e1);
			}
			app.updateAll();
		}
	}

	/**
	 * This function delete's a subscription. Before deleting it sends a confirm popup.
	 * @param subscription to delete
	 */
	private void deleteSubscriptionEvent(final Subscription subscription) {
		String question = "Ben je zeker dat je de inschrijving van " + subscription.getClient().getName() + 
								"voor de workshop " + workshop.getTitle() + " wil annuleren?";
		Confirm confirmDialog = new Confirm(getShell(), "Inschrijving annuleren?", question);
		if (confirmDialog.open().accepted) {	
			try {
				app.getSubscriptionList().delete(subscription);
			} catch (SQLException e1) {
				app.dbCommunicationException(e1);
			}			
			app.updateAll();								
		}
	}
	
	/**
	 * This function change the totalText on the top of the subscription field. After changing it calls a redraw function.
	 * @param text
	 */
	private void setTotalText(String text) {
		totalText.setText(text);
		// Force redraw (SWT doesn't seem to do this always)
		totalText.redraw();
	}

	/**
	 * This function adds a new line to with a subscripted client to the subscription field.
	 * @param subscription that you want to add to the subscription field.
	 */
	private void addToGuiList(final Subscription subscription) {
		Client client = subscription.getClient();
		final String name = client.getGivenname() + " " + client.getLastname();
		
		Text text = new Text(this, SWT.READ_ONLY | SWT.WRAP | SWT.MULTI);
		text.setText(name);
		GridData span2 = new GridData();
		span2.horizontalSpan = 2;
		text.setLayoutData(span2);
		
		Button removeButton = new Button(this, SWT.PUSH);
		removeButton.setText("x");
		GridData alignRight = new GridData();
		alignRight.horizontalAlignment = GridData.END;
		removeButton.setLayoutData(alignRight);
		
		removeButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {		
				deleteSubscriptionEvent(subscription);			
			}
		});	
		
		guiList_text.add(text);
		guiList_button.add(removeButton);
	}
	
	/**
	 * this function disposes all existing lines of subscripted clients.
	 */
	private void disposeGuiList() {
		for (Control control : guiList_text) {
			control.dispose();
		}
		for (Control control : guiList_button) {
			control.dispose();
		}
	}
}
